package com.sensor.Manager;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

import com.alibaba.fastjson.JSON;
import com.landmesure.communication.BaseManager;
import com.landmesure.communication.CommunicationPlatform;
import com.landmesure.communication.MonitorItemDecode;
import com.landmesure.communication.SendMessageService;
import com.landmesure.core.TestMessage;
import com.sensor.core.HandlerMessage;
import com.sensor.core.Sensor;
import com.sensor.core.Task;
import com.util.EncodeUtil;
import com.util.OkHttpUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.content.ContentValues.TAG;
import static com.code.DataType.CODE_ERROR;
import static com.code.DataType.CODE_HISTROYDATA;
import static com.code.DataType.CODE_OBJECTDATA;
import static com.code.DataType.CODE_PARAM;
import static com.code.DataType.CODE_STATUSDATA;
import static com.code.DataType.CODE_STATUS_TESTDATA;
import static com.code.DataType.CODE_SUCCESS;
import static com.code.DataType.CODE_SUCCESS_QUERYDATA;
import static com.code.DataType.CODE_SUCCESS_TEST;
import static com.code.DataType.CODE_TESTDATA;
public class GangXuanShiShenYaJiManager extends BaseManager {

    public List<String> projectList = new ArrayList<>();
    public Map<String, Integer> projectMap = new HashMap<>();
    public ArrayList<Sensor> senSors=new ArrayList<>() ;
    private final static int TEST_PCODE = 101;
    private final static int YALIE_CODE = 147;
    public int currentTimes;
    private Map<Integer, ArrayList<Double>> dataMap = new HashMap<>();
    private  List<Task> tasks=new ArrayList<>();
    public GangXuanShiShenYaJiManager(Handler handler) {
        this.handler = handler;
    }

    protected void switchMessage(String ms) {
        int dataType = getDataType(ms);
        switch (dataType) {
            case CODE_TESTDATA:
                processTestMessage(ms);
                break;
            case CODE_STATUSDATA:
                break;
            case CODE_SUCCESS:
                break;
            case CODE_PARAM:
                break;
            case CODE_OBJECTDATA:
                break;
            case CODE_ERROR:
                break;
            case CODE_HISTROYDATA:
                break;
            case CODE_SUCCESS_QUERYDATA:
                break;
            case CODE_SUCCESS_TEST:
                processTestMessage(ms);
                break;
            case CODE_STATUS_TESTDATA:
                break;
            default:
                break;
        }
    }


    public void processRcvMessage(String readMessage) {
        Log.i(TAG, "yuanprocessReadMessage: " + readMessage);
        CommunicationPlatform.deadlineTime = System.currentTimeMillis() + CommunicationPlatform.OVER_TIME;
        appendMessage(readMessage, totalMessage);
        processScodeForDecode();
    }



    private void processTestMessage(String ms) {
        int ecode = Integer.parseInt(ms.substring(26, 30), 16);
        if (isBZDL(ms, ecode)) return;
        processSYJ(ms, ecode);

    }

    private void processSYJ(String ms, int ecode) {
        for (Task task:tasks){
            Log.i(TAG, "processSYJ: "+ms);
            if (ecode == task.getEcode()) {
                TestMessage testMessage = monitorItemDecode(ms, "频率模数");
                if (testMessage == null) {
                    return;
                }
                ArrayList<Double> values = dataMap.get(ecode);
                double value = Double.parseDouble(testMessage.getValue());
                if (values == null) {
                    values = new ArrayList<>();
                    values.add(value);
                    dataMap.put(ecode, values);
                } else {
                    values.add(value);
                }
                increaseCurrentTimes();
                testMessage.setEcode(ecode);
                sendTestMessage2Fragment(testMessage, HandlerMessage.ShengYaJi.READ_SYJ);
            }

        }
    }

    /*
    更新当前测量次数
     */
    private void increaseCurrentTimes() {
        currentTimes++;
    }

    private boolean isBZDL(String ms, int ecode) {
        if (ecode == YALIE_CODE) {
            TestMessage testMessage = monitorItemDecode(ms, "电流");
            if (testMessage == null) {
                return false;
            }
            testMessage.setEcode(ecode);
            testMessage.setValue(String.valueOf(1000.0 / 16 * (Double.parseDouble(testMessage.getValue()) - 4)));
            sendTestMessage2Fragment(testMessage, HandlerMessage.ShengYaJi.READ_BZDL);
            return true;
        }
        return false;
    }

    private TestMessage monitorItemDecode(String ms, String itemName) {
        List<TestMessage> testMessages;
        try {
            testMessages = MonitorItemDecode.decodeMonitorItem(ms);
            for (TestMessage t : testMessages
            ) {
                if (itemName.equals(t.getName())) {
                    return t;
                }
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void serProject(final Spinner projectSpinner, final ArrayAdapter<String> adapter) {
        Map<String, Object> map = new HashMap<>();
        map.put("tableName", "工程基本表");
        map.put("actionName", "取表");
        String json = JSON.toJSONString(map);
        Log.i(TAG, "yuanpostTest: " + json);
        String url = CommunicationPlatform.url;
        try {
            OkHttpUtil okHttpUtil = OkHttpUtil.getInstance();
            okHttpUtil.sendJson(url, json, new OkHttpUtil.Fun4() {
                @Override
                public void onResponse(JSONObject jsonObject) throws JSONException {
                    JSONArray contents = jsonObject.getJSONArray("content");
                    for (int i = 0; i < contents.length(); i++) {
                        JSONObject content = (JSONObject) contents.get(i);
                        projectList.add(String.valueOf(content.get("工程名称")));
                        projectMap.put(String.valueOf(content.get("工程名称")), Integer.parseInt(String.valueOf(content.get("工程号"))));
                    }
                    projectSpinner.setAdapter(adapter);
                    Log.i(TAG, "yuanonResponse: " + jsonObject);
                }

                @Override
                public void onFailure() {
                    Message msg = new Message();
                    msg.what = HandlerMessage.ShengYaJi.SER_PROJECT_ERROR;
                    handler.sendMessage(msg);
                    Log.i(TAG, "yuanonResponse: 请求失败" );
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    private void beforeReadStart(){
        //清空数据
        dataMap.clear();
        currentTimes = 0;
        tasks.clear();
        creatTask();
    }
    public void readStart(int times, int station, int group) {
        beforeReadStart();
        SendMessageService sendMessageService = new SendMessageService();
        for (Task task : tasks) {
            for (int i = 0; i < times; i++) {
                String message = EncodeUtil.combineMessageForSelectTest(TEST_PCODE, getStationGroup(station, group), task.getEcode());
                try {
                    sendMessageService.sendMessage(null, HandlerMessage.ShengYaJi.READ_SYJ, null, message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
    }

    public void getGroup() {
        senSors.clear();
        Map<String, Object> map = new HashMap<>();
        map.put("tableName", "检验分组");
        map.put("actionName", "查询分组信息");
        String json = JSON.toJSONString(map);
        Log.i(TAG, "yuanpostTest: " + json);
        String url = CommunicationPlatform.url;
        try {
            OkHttpUtil okHttpUtil = OkHttpUtil.getInstance();
            okHttpUtil.sendJson(url, json, new OkHttpUtil.Fun4() {
                @Override
                public void onResponse(JSONObject jsonObject) throws JSONException {
                    JSONArray contents = jsonObject.getJSONArray("content");
                    for (int i = 0; i < contents.length(); i++) {
                        JSONObject content = (JSONObject) contents.get(i);
                        Sensor senSor = new Sensor();
                        senSor.setEcode(Integer.parseInt(String.valueOf(content.get("对象编号"))));
                        senSor.setEid(Integer.parseInt(String.valueOf(content.get("对象编码"))));;
                        senSors.add(senSor);
                    }
                    Message msg = new Message();
                    msg.what = HandlerMessage.ShengYaJi.GET_GROUP_SUCCESS;
                    handler.sendMessage(msg);
                    Log.i(TAG, "yuanonResponse: " + jsonObject);
                }

                @Override
                public void onFailure() {
                    Message msg = new Message();
                    msg.what = HandlerMessage.ShengYaJi.GET_GROUP_ERROR;
                    handler.sendMessage(msg);
                    Log.i(TAG, "yuanonResponse: 请求失败" );
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void creatTask() {
        for (Sensor sensor:senSors
             ) {
            Task task=new Task();
            task.setEcode(sensor.getEcode());
            task.setEid(sensor.getEid());
            task.setOverTime(1000*60);
            tasks.add(task);
        }
    }

    private String getStationGroup(int station, int group) {
        return String.format("%04X", (station << 6) + group);
    }

    public void save(int cehui, int pcode, double biaoZhunZhi,double currentYali) {
        Map<String, Object> map = new HashMap<>();
        List<Map> dataList = new ArrayList<>();
        map.put("tableName", "检验分组");
        map.put("actionName", "保存检验数据");
        map.put("测回", cehui);
        map.put("标准值", biaoZhunZhi);
        map.put("标准传感器值", currentYali);
        map.put("工程号", pcode);
        map.put("pcode", pcode);
        map.put("data", dataList);
        filterData();
        getMeasureData(dataList);
        String json = JSON.toJSONString(map);
        Log.i(TAG, "yuanpostTest: " + json);
        String url = CommunicationPlatform.url;
        try {
            OkHttpUtil okHttpUtil = OkHttpUtil.getInstance();
            okHttpUtil.sendJsonPcode(url, json, String.valueOf(pcode), new OkHttpUtil.Fun4() {
                @Override
                public void onResponse(JSONObject jsonObject) {
                    try {
                        String message = jsonObject.getString("message");
                        if (!message.equals("数据校验失败")){
                            Message msg = new Message();
                            Bundle data = new Bundle();
                            data.putString("data", message);
                            msg.what = HandlerMessage.ShengYaJi.SAVE_SYJ_DATA_SUCCESS;
                            msg.setData(data);
                            handler.sendMessage(msg);
                        }
                        else {
                            JSONObject content = jsonObject.getJSONObject("content");
                            String ceHui = content.getString("测回");
                            Message msg = new Message();
                            Bundle data = new Bundle();
                            data.putString("data", "第"+ceHui+"数据有误，请重新测量");
                            msg.what = HandlerMessage.ShengYaJi.SAVE_SYJ_DATA_SUCCESS;
                            msg.setData(data);
                            handler.sendMessage(msg);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    Log.i(TAG, "yuanonResponse: " + jsonObject);
                }

                @Override
                public void onFailure() {
                    Message msg = new Message();
                    msg.what = HandlerMessage.ShengYaJi.SAVE_DATA_ERROR;
                    handler.sendMessage(msg);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
    获取测量数据
     */
    private void getMeasureData(List<Map> dataList) {
        for (Map.Entry<Integer, ArrayList<Double>> entry : dataMap.entrySet()) {
            double sum = 0;
            double value;
            int size = entry.getValue().size();
            for (int i = 0; i < size; i++) {
                sum += entry.getValue().get(i);
            }
            value = sum / size;
            Map<Integer, Object> m = new HashMap();
            m.put(getEidByEcode(entry.getKey()), value);
            dataList.add(m);
        }
    }

    /*
    去掉最大最小值
     */
    private void filterData() {
        for (Map.Entry<Integer, ArrayList<Double>> entry : dataMap.entrySet()) {
            ArrayList<Double> values = entry.getValue();
            if (values.size() > 2) {
                Double max = Collections.max(values);
                Double min = Collections.min(values);
                values.remove(max);
                values.remove(min);
            }

        }
    }

    private Integer getEidByEcode(int ecode) {
        for (Sensor s : senSors
        ) {
            if (s.getEcode() == ecode) {
                return s.getEid();
            }
        }

        return null;
    }

    public void readYaLi(int station, int group) {
        String message = EncodeUtil.combineMessageForSelectTest(TEST_PCODE, getStationGroup(station, group), YALIE_CODE);
        SendMessageService sendMessageService = new SendMessageService();
        try {
            sendMessageService.sendMessage(null, HandlerMessage.ShengYaJi.READ_BZDL, null, message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
